/*
 *所有关于API_AI_Log类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*API_AI_LogService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using VOL.Core.BaseProvider;
using VOL.Core.Extensions.AutofacManager;
using VOL.Entity.DomainModels;
using System.Linq;
using VOL.Core.Utilities;
using System.Linq.Expressions;
using VOL.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.System.IRepositories;
using System.Net;
using System.Text.Json;
using System.Collections.Generic;
using VOL.Core.ManageUser;
using System;
using System.IO;
using System.Text;
using Org.BouncyCastle.Asn1.Ocsp;

namespace VOL.System.Services
{
    public partial class API_AI_LogService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IAPI_AI_LogRepository _repository;//访问数据库

        [ActivatorUtilitiesConstructor]
        public API_AI_LogService(
            IAPI_AI_LogRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        public override PageGridData<API_AI_Log> GetPageData(PageDataOptions options)
        {
            API_AI_Log aPI_AI_Log = null;

            RequestAI requestAI = null;




            if (options.Wheres != null)//(整刀组装
            {
                aPI_AI_Log=new API_AI_Log();
                var options1 = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true // 忽略属性名的大小写
                };

                 var items =JsonSerializer.Deserialize<List<Wheres>>(options.Wheres, options1);
                 foreach (var item in items)
                 {
                     if (item.name == "ProjectCode")
                     {
                         aPI_AI_Log.ProjectCode = item.value;
                     }
                     if (item.name == "ProjectName")
                     {
                         aPI_AI_Log.ProjectName = item.value;
                  
                     }
                     if(item.name== "AskContent")
                     {
                         aPI_AI_Log.AskContent = item.value;
                     }
                     if(item.name=="RoleSystem")
                     {
                         aPI_AI_Log.RoleSystem = item.value;
                     }

                 }

        
               

                if (aPI_AI_Log.AskContent!=null)
                 {

                    string output = string.Empty;
                    try
                    {
                        string url = "https://ark.cn-beijing.volces.com/api/v3/chat/completions";
                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                        request.ContentType = "application/json";
                        request.Method = "POST"; // 或者 "POST", "PUT", "DELETE" 等
                        request.Accept = "application/json";
                        request.Headers.Add("Authorization", " Bearer 34156ca4-2569-4a97-bcc8-cd16d445fa2d"); // 如果需要认证的话
                        Stream stream = request.GetRequestStream();
                        //string json = "{\"model\":\"deepseek-r1-250120\",\"messages\":[{\"role\":\"system\",\"content\":\"你是人工智能助手.\"},{\"role\":\"user\",\"content\":\"常见的十字花科植物有哪些？\"}]}";
                        if(aPI_AI_Log.RoleSystem==null)
                        {
                            aPI_AI_Log.RoleSystem = "你是人工智能助手.";
                        }
                        string json = "{\"model\":\"deepseek-r1-250120\",\"messages\":[{\"role\":\"system\",\"content\":\""+aPI_AI_Log.RoleSystem+".\"},{\"role\":\"user\",\"content\":\"" + aPI_AI_Log.AskContent + "\"}]}";
                        byte[] buffer = Encoding.UTF8.GetBytes(json);
                        stream.Write(buffer, 0, buffer.Length);
                        stream.Close();
                        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                        {
                            if (response.StatusCode == HttpStatusCode.OK)
                            {
                                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                                {
                                    string content = reader.ReadToEnd();
                                   
                                    //   requestAI=    Newtonsoft.Json.JsonConvert.DeserializeObject<RequestAI>(aPI_AI_Log.AnswerContent);
                                    requestAI=JsonSerializer.Deserialize<RequestAI>(content, options1);
                                    aPI_AI_Log.AnswerContent = requestAI.choices[0].message.reasoning_content;

                                }
                            }
                            else
                            {
                                Console.WriteLine($"Error: {response.StatusCode}");
                            }
                        }
                    }
                    catch (WebException e)
                    {
                        Console.WriteLine($"Exception Caught! {e.Message}");
                    }
                    aPI_AI_Log.CreateOn = DateTime.Now;
                    aPI_AI_Log.CreateBy = UserContext.Current.UserName;


                    //    var items =  JsonConvert.DeserializeObject<List<Wheres>>(options.Wheres);
                  
                    _repository.DbContext.Set<API_AI_Log>().Add(aPI_AI_Log);
                    _repository.DbContext.SaveChanges();
                }
                
            }
           
            return base.GetPageData(options);
        }
    }
}
